package cn.mothin.service.system;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.bean.easyui.DataContent;
import cn.mothin.bean.system.OrganizationTreeData;
import cn.mothin.dao.OrganizationDao;
import cn.mothin.dao.SystemUserDao;
import cn.mothin.entity.Organization;
import cn.mothin.frame.bean.ActionResult;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.StringUtil;
import cn.mothin.vo.system.OrganizationForm;

@Service("540ec121a62120babb8094c1")
public class OrganizationService {
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private SystemUserDao systemUserDao;

    private void addSub(OrganizationTreeData organizationTreeData) {
        List<Organization> organizations = organizationDao.queryOrganizations(organizationTreeData.getId());
        for (int i = 0; i < organizations.size(); i++) {
            Organization organization = organizations.get(i);
            OrganizationTreeData sub = new OrganizationTreeData();
            sub.setId(organization.getId());
            sub.setMemo(organization.getMemo());
            sub.setOrganizationName(organization.getOrganizationName());
            sub.setManager(organization.getManager());
            addSub(sub);
            organizationTreeData.addChild(sub);
        }
    }

    /**
     * 查询全部的机构类JSON数据
     * 
     * @param organizationForm
     *            VO
     * @param includeFields
     *            被包含的字段
     * @return
     */
    public List<OrganizationTreeData> queryOrganization(OrganizationForm organizationForm) {
        List<OrganizationTreeData> list = new ArrayList<OrganizationTreeData>();
        List<Organization> organizations = organizationDao.queryOrganizations(null);
        for (int i = 0; i < organizations.size(); i++) {
            Organization organization = organizations.get(i);
            OrganizationTreeData sub = new OrganizationTreeData();
            sub.setId(organization.getId());
            sub.setMemo(organization.getMemo());
            sub.setOrganizationName(organization.getOrganizationName());
            sub.setManager(organization.getManager());
            addSub(sub);
            list.add(sub);
        }
        return list;
    }

    public void query(OrganizationForm organizationForm) {
        organizationForm.setOrganization(organizationDao.get(organizationForm.getId()));
    }

    public List<Organization> findByName(String name) {
        String hql = "SELECT * FROM organization WHERE deleted<>TRUE AND organizationName=?";
        return organizationDao.query(hql, name);
    }

    public List<Organization> findByNameAndPid(String name, String parentId) {
        String hql = "SELECT * FROM organization WHERE deleted<>TRUE AND organizationName=? and parentId=?";
        return organizationDao.query(hql, name, parentId);
    }

    /**
     * 手动添加新机构
     * 
     * @param dictionaryForm
     *            VO
     * @param loginUser
     *            登录用户
     * @return
     */
    public ActionResult addOrganization(OrganizationForm organizationForm) {
        ActionResult result = ActionResult.getInstance();
        if (StringUtil.isNullOrEmpty(organizationForm.getOrganization()
                .getParentId())) {
            if (findByName(
                    organizationForm.getOrganization().getOrganizationName())
                    .size() > 0) {
                result.setOk(false);
                result.setMessage("相同名称的角色已存在");
                return result;
            }
        } else {
            if (findByNameAndPid(
                    organizationForm.getOrganization().getOrganizationName(),
                    organizationForm.getOrganization().getParentId()).size() > 0) {
                result.setOk(false);
                result.setMessage("相同名称的角色已存在");
                return result;
            }
        }
        String id = UniqueCode.make();
        Organization organization = new Organization();
        organization.setId(id);
        organization.setOrganizationName(organizationForm.getOrganization()
                .getOrganizationName());
        organization.setDeleted(false);
        organization.setMemo(organizationForm.getOrganization().getMemo());
        if (organizationForm.getOrganization().getParentId().equals("")) {
            organization.setParentId(null);
        } else {
            organization.setParentId(organizationForm.getOrganization()
                    .getParentId());
        }
        this.organizationDao.save(organization);
        result.setValue(id);
        return result;
    }

    /**
     * 查询机构
     * 
     * @param organizationForm
     *            VO
     * @return
     */
    public ActionResult queryOrganizationForUpdate(
            OrganizationForm organizationForm) {
        ActionResult result = ActionResult.getInstance();
        Organization organization = organizationDao.get(organizationForm
                .getOrganization().getId());
        if (organization == null) {
            result.setOk(false);
            result.setMessage("指定的机构不存在！");
            return result;
        } else if (organization.isDeleted()) {
            result.setOk(false);
            result.setMessage("此机构已被删除！");
            return result;
        }
        organizationForm.getOrganization().setOrganizationName(
                organization.getOrganizationName());
        organizationForm.getOrganization().setMemo(organization.getMemo());
        organizationForm.getOrganization().setParentId(
                organization.getParentId());
        return result;
    }

    public List<Organization> findByParameter(String name, String parentId,
            String memo) {
        String hql = "SELECT * FROM organization WHERE deleted<>TRUE AND organizationName=? and parentId=? and memo=?";
        return organizationDao.query(hql, name, parentId, memo);
    }

    /**
     * 部门更新名称重复查询
     * 
     * @param name
     * @param id
     * @return
     */
    public List<Organization> findByNameWithOutId(String name, String id) {
        String hql = "SELECT * FROM organization WHERE organizationName=? AND parentId IS NULL AND id<>? AND deleted<>TRUE";
        return organizationDao.query(hql, name, id);
    }

    public List<Organization> findByNameAndPidWithOutId(String name,
            String parentId, String id) {
        String hql = "SELECT * FROM organization WHERE organizationName=? AND parentId=? AND id<>? AND deleted<>TRUE";
        return organizationDao.query(hql, name, parentId, id);
    }

    /**
     * 修改机构
     * 
     * @param organizationForm
     *            VO
     * @param loginUser
     *            登录用户
     * @return
     */
    public ActionResult updateOrganization(OrganizationForm organizationForm) {
        ActionResult result = ActionResult.getInstance();
        String id = organizationForm.getOrganization().getId();
        String name = organizationForm.getOrganization().getOrganizationName();
        String pid = organizationForm.getOrganization().getParentId();
        String memo = organizationForm.getOrganization().getMemo();
        Organization organization = organizationDao.get(id);
        if (organization == null) {
            result.setOk(false);
            result.setMessage("指定的机构不存在！");
            return result;
        } else if (organization.isDeleted()) {
            result.setOk(false);
            result.setMessage("此机构已被删除！");
            return result;
        } else if (StringUtil.isNullOrEmpty(organizationForm.getOrganization()
                .getParentId())) {
            if (findByNameWithOutId(name, id).size() > 0) {
                result.setOk(false);
                result.setMessage("相同名称的角色已存在");
                return result;
            }
        } else {
            if (findByNameAndPidWithOutId(name, pid, id).size() > 0) {
                result.setOk(false);
                result.setMessage("相同名称的角色已存在");
                return result;
            }
        }
        organization.setMemo(memo);
        organization.setOrganizationName(organizationForm.getOrganization()
                .getOrganizationName());
        organizationDao.update(organization);
        return result;
    }

    /**
     * 删除指定的机构
     * 
     * @param organizationForm
     *            VO
     * @param loginUser
     *            登录用户
     * @return
     */
    public ActionResult deleteOrganization(OrganizationForm organizationForm) {
        ActionResult result = ActionResult.getInstance();
        String id = organizationForm.getOrganization().getId();
        Organization organization = organizationDao.get(id);
        if (organization == null) {
            result.setOk(false);
            result.setMessage("指定的此机构不存在！");
            return result;
        } else if (organization.isDeleted()) {
            result.setOk(false);
            result.setMessage("此机构已被删除！");
            return result;
        }
        // 查出该部门下的子部门
        List<String> childOrgList = organizationDao.queryChild(id);
        if (childOrgList != null && childOrgList.size() > 0) {
            result.setOk(false);
            result.setMessage("因存在人员或子部门，此机构暂不能删除！");
            return result;
        }
        // 查出该部门下的人员
        List<String> systemUser = systemUserDao.querySystemUser(id);
        if (systemUser != null && systemUser.size() > 0) {
            result.setOk(false);
            result.setMessage("因存在人员或子部门，此机构暂不能删除！");
            return result;
        }
        organization.setDeleted(true);
        organizationDao.update(organization);
        return result;
    }

    /**
     * 根据组织机构id查询该部门下的系统用户
     * 
     * @param organizationForm
     *            VO
     * @return
     */
    public String selectManager(OrganizationForm organizationForm) {
        String sql = "SELECT id,name FROM system_user WHERE organizationId = ? AND deleted <> TRUE ";
        String orgId = organizationForm.getOrganization().getId();
        return systemUserDao.queryJson(sql, orgId);
    }

    /**
     * 更新部门负责人
     * 
     * @param organizationForm
     *            VO
     * @return
     */
    public ActionResult updateManager(OrganizationForm organizationForm) {
        ActionResult result = ActionResult.getInstance();
        String id = organizationForm.getOrganization().getId();
        Organization organization = organizationDao.get(id);
        if (organization == null) {
            result.setOk(false);
            result.setMessage("负责人设置失败");
            return result;
        }
        String manager = organizationForm.getOrganization().getManager();
        if (StringUtil.isNullOrEmpty(manager) || manager.trim().equals("请选择")) {
            organization.setManager(null);
        } else {
            organization.setManager(manager);
        }
        organizationDao.update(organization);
        return result;
    }
    
    
    private void addSub(DataContent dataContent,List<String> selected) {
        List<Organization> organizations = organizationDao.queryOrganizations(dataContent.getId());
        for (int i = 0; i < organizations.size(); i++) {
            Organization organization = organizations.get(i);
            DataContent sub = new DataContent();
            sub.setId(organization.getId());
            sub.setText(organization.getOrganizationName());
            if(selected.size()>0&&selected.contains(organization.getId())){
                sub.setChecked(true);
            }
            addSub(sub,selected);
            dataContent.addChild(sub);
        }
    }
    
    public List<DataContent> queryControlOrganization(OrganizationForm organizationForm) {
        List<String> selected=new ArrayList<String>();
        if(!StringUtil.isNullOrEmpty(organizationForm.getSelected())){
            String[] ss=organizationForm.getSelected().split(",");
            for(int i=0;i<ss.length;i++){
                selected.add(ss[i]);
            }
        }
        
        List<DataContent> list = new ArrayList<DataContent>();
        List<Organization> organizations = organizationDao.queryOrganizations(null);
        for (int i = 0; i < organizations.size(); i++) {
            Organization organization = organizations.get(i);
            DataContent sub = new DataContent();
            sub.setId(organization.getId());
            sub.setText(organization.getOrganizationName());
            if(selected.size()>0&&selected.contains(organization.getId())){
                sub.setChecked(true);
            }
            addSub(sub,selected);
            list.add(sub);
        }
        return list;
    }

}
